package com.sun.filesigndemo.common.security;

import com.sun.filesigndemo.common.redis.CacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Cache工具类
 * @author winkey
 * @version 2017-11-06
 */
@Component
public class CacheUtils {
	
	private static Logger logger = LoggerFactory.getLogger(CacheUtils.class);
	private static CacheService cacheService;
	
	private static final String SYS_CACHE = "sysCache";

	@Autowired
	public CacheUtils(CacheService cacheService) {
		CacheUtils.cacheService= cacheService;
	}
	
	/**
	 * 获取SYS_CACHE缓存
	 * @param key
	 * @return
	 */
	public static Object get(String key) {
		return get(SYS_CACHE, key);
	}
	
	/**
	 * 获取SYS_CACHE缓存
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static Object get(String key, Object defaultValue) {
		Object value = get(key);
		return value != null ? value : defaultValue;
	}
	
	/**
	 * 写入SYS_CACHE缓存
	 * @param key
	 * @return
	 */
	public static void put(String key, Object value) {
		put(SYS_CACHE, key, value);
	}
	
	/**
	 * 从SYS_CACHE缓存中移除
	 * @param key
	 * @return
	 */
	public static void remove(String key) {
		remove(SYS_CACHE, key);
	}
	
	/**
	 * 获取缓存
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static Object get(String cacheName, String key) {
		return cacheService.getHash(cacheName,key);
	}
	
	/**
	 * 获取缓存
	 * @param cacheName
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static Object get(String cacheName, String key, Object defaultValue) {
		Object value = get(cacheName, key);
		return value != null ? value : defaultValue;
	}
	
	/**
	 * 写入缓存
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put(String cacheName, String key, Object value) {
		cacheService.putHash(cacheName, key, value);
	}

	/**
	 * 从缓存中移除
	 * @param cacheName
	 * @param key
	 */
	public static void remove(String cacheName, String key) {
		cacheService.deleteHash(cacheName, key);
	}

	/**
	 * 从缓存中移除所有
	 * @param cacheName
	 */
	public static void removeAll(String cacheName) {
		cacheService.deleteHash(cacheName);
	}
	
	/**
	 * 
	 * @param key
	 * @param value
	 * @param exp 秒
	 */
	public static void setExp(String key, Object value, Long exp) {
		cacheService.set(key, value, exp);
	}
	@SuppressWarnings("unchecked")
	public static <T> T getExp(String key) {
		return (T)cacheService.get(key);
	}
	public static Boolean delete(String key) {
		return cacheService.delete(key);
	}
}
